package main

import (
	"context"
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/stream_grpc_test/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/protobuf/types/known/timestamppb"
	"sync"
	"time"
)

func main() {
	conn, err := grpc.NewClient("127.0.0.1:8081", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	c := proto.NewGreeterClient(conn)

	//// 服务端流模式
	//res, _ := c.GetStream(context.Background(), &proto.StreamReqData{Data: "慕课网，程序员的梦工厂"})
	//for {
	//	a, err := res.Recv()
	//	if err != nil {
	//		fmt.Println(err)
	//		break
	//	}
	//	fmt.Println(a)
	//}
	//
	//// 客户端流模式
	//putS, _ := c.PutStream(context.Background())
	//i := 0
	//for {
	//	i++
	//	_ = putS.Send(&proto.StreamReqData{
	//		Data: fmt.Sprintf("发送数据 %d", i),
	//	})
	//	time.Sleep(time.Second)
	//	if i > 10 {
	//		break
	//	}
	//}

	// 双向流模式
	allStr, _ := c.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := allStr.Recv()
			fmt.Println("收到服务端发送的消息为：", data.Data, data.Mp)
		}
	}()

	go func() {
		defer wg.Done()
		for {
			allStr.Send(&proto.StreamReqData{
				Data:    "我是客户端，正在给服务器端发送消息",
				G:       proto.Gender_MALE,
				AddTime: timestamppb.New(time.Now()),
			})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
}
